#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

int delay;
int n,m;

typedef struct TNode {
	int idx;
	char type;
	int delay;
} TNode;

vector<TNode> nodes;
vector<int> adjs[2000];
vector<int> emptyV;
bool visit[2000];
bool visiting[2000];
int dist[2000][2000];

bool findCircle(void) {

	memset(visit, 0, n);
	memset(visiting, 0, n);

	vector<int> rootStack;
	bool newRoot;

	for (int i=0; i<n; ++i) {
		if (visit[i]) continue;
		int root = i;
		while (true) {
			visit[root] = true;
			visiting[root] = true;
			newRoot = false;
			for (int j=0; j<adjs[root].size(); ++j) {
				if (nodes[adjs[root][j]].type != 'a') continue;
				if (visiting[adjs[root][j]])
					return true;
				if (visit[adjs[root][j]]) continue;
				rootStack.push_back(root);
				root = adjs[root][j];
				newRoot = true;
				break;
			}
			if (!newRoot) {
				visiting[root] = false;
				if (rootStack.size() == 0) break;
				root = rootStack[rootStack.size()-1];
				rootStack.pop_back();
			}
		}
	}

	return false;
}

int findLongest(void) {
	
	for (int i=0; i<n; ++i) {
		for (int j=0; j<n; ++j)
			dist[i][j] = 1050000000;
		dist[i][i] = 0;
	}

	int minV = 0;
	for (int i=0; i<n; ++i) {
		for (int j=0; j<adjs[i].size(); ++j) {
			if (nodes[i].type == 'a') {
				dist[i][adjs[i][j]] = -nodes[i].delay;
				if (minV > dist[i][adjs[i][j]]) minV = dist[i][adjs[i][j]];
			}
			else dist[i][adjs[i][j]] = 1050000000;
		}
	}

// 	for (int i=0; i<n; ++i) {
// 		for (int j=0; j<n; ++j)
// 			cout << dist[i][j] << " ";
// 		cout << endl;
// 	}
	for (int k=0; k<n; ++k) {
// 		cout << "k: " << k << endl;
		for (int i=0; i<n; ++i) {
			for (int j=0; j<n; ++j) {
				if (dist[i][k]+dist[k][j]<dist[i][j]) {
					dist[i][j] = dist[i][k] + dist[k][j];
					if (dist[i][j] < minV) minV = dist[i][j];
				}
			}
		}
// 
// 		for (int i=0; i<n; ++i) {
// 			for (int j=0; j<n; ++j)
// 				cout << dist[i][j] << " ";
// 			cout << endl;
// 		}
// 		cout << endl;

	}


	return -minV;
}

int main(void)
{
	int testcase;
	cin >> testcase;
	for (int i=0; i<testcase; ++i) {
		cin >> delay;
		cin >> n;
		nodes.clear();
		for (int j=0; j<n; ++j) {
			char c;
			int d;
			cin >> c >> d;
			TNode t;
			t.idx = j;
			t.type = c;
			t.delay = d;
			nodes.push_back(t);
			adjs[j].clear();
		}
		cin >> m;
		for (int j=0; j<m; ++j) {
			int a, b;
			cin >> a >> b;
			adjs[a].push_back(b);
		}

		if (findCircle()) {
			cout << "Circuit contains cycle." << endl;
		}
		else {
			int ld = findLongest();
			if (ld > delay)
				cout << "Clock period exceeded." << endl;
			else
				cout << "Synchronous design. Maximum delay: " << ld << "." << endl;
		}
	}
	return 0;
}